/**
 * 统一错误代码定义
 */
export const ERROR_CODES = {
  // 认证错误 (1xxx)
  INVALID_CREDENTIALS: 1001,
  TOKEN_EXPIRED: 1002,
  TOKEN_INVALID: 1003,
  ACCOUNT_LOCKED: 1004,
  ACCOUNT_DISABLED: 1005,
  TWO_FA_REQUIRED: 1006,
  TWO_FA_INVALID: 1007,
  
  // 权限错误 (2xxx)
  PERMISSION_DENIED: 2001,
  INSUFFICIENT_PRIVILEGES: 2002,
  
  // 资源错误 (3xxx)
  USER_NOT_FOUND: 3001,
  TOKEN_NOT_FOUND: 3002,
  CATEGORY_NOT_FOUND: 3003,
  SESSION_NOT_FOUND: 3004,
  
  // 验证错误 (4xxx)
  VALIDATION_ERROR: 4001,
  DUPLICATE_ENTRY: 4002,
  INVALID_INPUT: 4003,
  PASSWORD_TOO_WEAK: 4004,
  
  // 系统错误 (5xxx)
  INTERNAL_ERROR: 5001,
  DATABASE_ERROR: 5002,
  SERVICE_UNAVAILABLE: 5003,
};

/**
 * 自定义错误类
 */
export class AppError extends Error {
  constructor(code, message, statusCode = 400, details = null) {
    super(message);
    this.code = ERROR_CODES[code] || code;
    this.statusCode = statusCode;
    this.details = details;
    this.timestamp = new Date().toISOString();
    Error.captureStackTrace(this, this.constructor);
  }
}

/**
 * 认证错误
 */
export class AuthenticationError extends AppError {
  constructor(code, message, details = null) {
    super(code, message, 401, details);
  }
}

/**
 * 权限错误
 */
export class AuthorizationError extends AppError {
  constructor(code, message, details = null) {
    super(code, message, 403, details);
  }
}

/**
 * 资源未找到错误
 */
export class NotFoundError extends AppError {
  constructor(code, message, details = null) {
    super(code, message, 404, details);
  }
}

/**
 * 验证错误
 */
export class ValidationError extends AppError {
  constructor(code, message, details = null) {
    super(code, message, 400, details);
  }
}

/**
 * 冲突错误
 */
export class ConflictError extends AppError {
  constructor(code, message, details = null) {
    super(code, message, 409, details);
  }
}

/**
 * 速率限制错误
 */
export class RateLimitError extends AppError {
  constructor(message = 'Too many requests') {
    super('RATE_LIMIT_EXCEEDED', message, 429);
  }
}

/**
 * 格式化错误响应
 */
export function formatErrorResponse(error) {
  if (error instanceof AppError) {
    return {
      success: false,
      error: {
        code: error.code,
        message: error.message,
        status: error.statusCode,
        timestamp: error.timestamp,
        details: error.details,
      },
    };
  }
  
  // 未知错误
  return {
    success: false,
    error: {
      code: ERROR_CODES.INTERNAL_ERROR,
      message: process.env.NODE_ENV === 'production' 
        ? 'Internal server error' 
        : error.message,
      status: 500,
      timestamp: new Date().toISOString(),
    },
  };
}

/**
 * 格式化成功响应
 */
export function formatSuccessResponse(data, message = 'Success') {
  return {
    success: true,
    data,
    message,
  };
}


